﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Cemit.Awaiter;

namespace Cemit.Awaiter.Demo
{
    class DelayRandom
    {
        static readonly Random random;

        static DelayRandom()
        {
            random = new Random((int)DateTime.Now.ToFileTime());
        }

        public static AsyncAction<int> Next(int delay, int min, int max)
        {
            AsyncAction<int> action = new AsyncAction<int>();

            //模拟延迟（耗时）操作
            new Thread(() => 
            {
                //延迟一段时间
                Thread.Sleep(delay);

                if (min > max)
                {
                    action.ThrowException(new Exception("min不能大于max"));
                    return;
                }

                //调用结果，并运行调用者await之后的代码
                action.ReportResult(random.Next(min, max));

            }).Start();

            return action;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("start");
            LogRandom();
        }

        private static async void LogRandom()
        {
            int i = await DelayRandom.Next(2000, 100, 100);
            Console.WriteLine(i);

            //模拟报错
            //i = await DelayRandom.Next(2000, 1000, 100);
            //Console.WriteLine(i);
        }
    }
}
